#include <QyDebug.h>
#include "QpwAccountManager.h"

QpwXML::Values QpwAccount::values() const {

    QpwXML::Values values;
    values["username"] = username;
    values["password"] = password;
    values["accessLevel"] = quint32(accessLevel);

    return values;
}

void QpwAccount::setValues( const QpwXML::Values & values ) {

    username = values["username"].toString();
    password = values["password"].toString();
    accessLevel = AccessLevels( values["accessLevel"].toUInt() );

}

/*static */QString QpwAccount::accessLevelName( AccessLevels level ) {

    switch (level) {

    case GuestAccessLevel:
        return QString("guest");

    case UserAccessLevel:
        return QString("user");

    case AdminAccessLevel:
        return QString("admin");

    case DeveloperAccessLevel:
        return QString("developer");

    }

    return QString();
}

/**************************************************************************************************/

QpwAccountManager::QpwAccountManager( const QString & filePath )
    : QpwXML::DatabaseTemplate<QpwAccount>(filePath), checkIPType(NormalAddress)
{
}

bool QpwAccountManager::checkUser( const QString & username, const QString & password ) {

    QpwAccount * acc = account(username);

    if (acc) {

        return acc->password == password && !acc->authorised;
    }

    return false;
}

bool QpwAccountManager::loginUser( const QString & username, const QString & password ) {

    if ( checkUser( username, password ) ) {

        if ( QpwAccount * acc = account(username) )
            acc->authorised = true;

        return true;
    }

    return false;
}

void QpwAccountManager::logoutUser( const QString & username ) {

    if ( QpwAccount * acc = account(username) )
        acc->authorised = false;

}

bool QpwAccountManager::checkIp( const QHostAddress & address ) {

    switch (checkIPType) {

    case AllowAllAddress:
        return true;

    case BlockAllAddress:
        return address == QHostAddress::LocalHost;

    case AllowedOnlyAddress:
        return allowedIP.contains(address);

    case NormalAddress:
        return !blockedIP.contains(address);

    }

    return false;
}

quint32 QpwAccountManager::level( const QString & username ) {

    if ( QpwAccount * acc = account(username) )
        return acc->accessLevel;

    return QpwAccount::GuestAccessLevel;
}

QpwAccount * QpwAccountManager::account( const QString & username ) {

    foreach ( QpwAccount acc, rows.values() ) {

        if ( acc.username == username )
            return &rows[acc.uuid];

    }

    return 0;
}

/**************************************************************************************************/
